
const getData = async () => {
    const {result, code} = await fetch('/excelData').then((res) => res.json());
    if (code === 200) {
        return {
            state: true,
            result
        }
    } else {
        alert('数据获取失败');
        return {
            state: false,
            result: {
                header: [],
                data: []
            }
        }
    }
};

const createHeaderEl = (header) => {
    let res = '';
    header.forEach((item) => {
        // console.log(item);
        // const th = document.createElement('th');
        // th.innerText = item;
        // return th;
        res += `<th>${item}</th>`
    })
    return res;
};

const createTableBodyEl = (header, data) => {
    let res = ''
    data.forEach((dataItem) => {
        let tr = '<tr>';
        const tdElArr = header.map((headerItem) => {
            return `<td>${dataItem[headerItem]}</td>`
        })

        tr += tdElArr;
        tr += '</tr>'
        res += tr;
    });
    return res;
}

const getEl = (id) => {
    return document.getElementById(id);
}

const createElByData = ({header, data}) => {
    const headerEl = createHeaderEl(header);
    const tableBodyEl = createTableBodyEl(header, data);
    const headerBox = getEl('headTr');
    const bodyBox = getEl('tableBody');
    console.log(tableBodyEl)
    if (headerBox && bodyBox) {
        headerBox.innerHTML = headerEl.replaceAll(',', '');
    
        bodyBox.innerHTML = tableBodyEl.replaceAll(',', '');
    }
}

const init = async () => {
    const {state, result} = await getData();

    if (state) {
        createElByData(result);
    }
};

window.onload = () => {
    init();
};